//
//  SignInViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-5-20.
//  Copyright (c) 2014年 suplus. All rights reserved.
//
//  登录认证后，后台同步头像，把用户id写用appDelegate
//

#import "SignInViewController.h"
#import <MMDrawerController.h>
#import "NetworkAccessManager.h"
#import "UIAlertView+Kirinrin.h"
#import "SNSCropImageViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "BPush.h"
#import "Keychain.h"
#import "UtilHelper.h"
#import "EaseMob.h"
#import "UIAlertView+Kirinrin.h"

#import <AFNetworking/UIActivityIndicatorView+AFNetworking.h>

#define kCropPhotoSize      180

@interface SignInViewController (){
    NSOperationQueue *operationQueue;
}
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
@property (weak, nonatomic) IBOutlet UITextField *account;
@property (weak, nonatomic) IBOutlet UITextField *password;

@property (weak, nonatomic) IBOutlet UIImageView *userPhotoView;
@property (strong, nonatomic)UIImage *userPhoto;

@end

@implementation SignInViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSMutableDictionary *usernamepasswordKVPairs = (NSMutableDictionary *)[Keychain load:KEY_USERNAME_PASSWORD];
    _account.text = [usernamepasswordKVPairs objectForKey:KEY_USERNAME];
    _password.text = [usernamepasswordKVPairs objectForKey:KEY_PASSWORD];
    
    CALayer *layer = [self.userPhotoView layer];
    layer.borderColor = [[UIColor whiteColor] CGColor];
    layer.borderWidth = 2.0f;
    
    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    numberToolbar.barStyle = UIBarStyleDefault;
    numberToolbar.items = [NSArray arrayWithObjects:
                           [[UIBarButtonItem alloc]initWithTitle:NSLocalizedString(@"关闭", nil) style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad)],
                           [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc]initWithTitle:NSLocalizedString(@"下一个", nil) style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)],
                           nil];
    [numberToolbar sizeToFit];
    self.account.inputAccessoryView = numberToolbar;
}

-(void)viewDidAppear:(BOOL)animated{
    if ([self canAutoSignIn]) {
        [self signInAction:nil];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - control keyboard

// hide keyboard when touched background
- (IBAction)touchBackground:(id)sender {
    [self.view endEditing:YES];
}


#pragma mark - fix number pad next key handle keyboard next key
-(void)cancelNumberPad{
    [self.view endEditing:YES];
}

-(void)doneWithNumberPad{
    if ([self.account isFirstResponder]) {
        [self.password becomeFirstResponder];
    }
    //    [self.phoneNumber resignFirstResponder];
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

}


- (IBAction)signInAction:(UIButton *)sender {
//    [self gotoMainView];
    //check accont and password
    
    [self.view endEditing:YES];
    
    NSString *account = self.account.text;
    NSString *password = self.password.text;
    
    if (![UtilHelper isValidateMobile:account]) {
        [UIAlertView alertWithFormCheckError:FCErrorInvaildPhoneNumber];
        [self.account becomeFirstResponder];
        return;
    }
    
    if (password.length == 0) {
        NSString *alertTitle = NSLocalizedString(@"错误", nil);
        NSString *alertMessage = NSLocalizedString(@"密码不能为空!", nil);
        NSString *cancelButtonTitle = NSLocalizedString(@"确定", nil);
        UIAlertView *alertView =[[UIAlertView alloc] initWithTitle:alertTitle message:alertMessage delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }


//    [self.activityIndicator startAnimating];
    
    NSString *uriString = @"Account.json";
    NSDictionary *parameters = @{@"account": account, @"password": [UtilHelper md5LowCase:password]};
    
    // ???:是不是合成一个接口, userType没有用枚举，写起来不舒服
    AFHTTPRequestOperation *opernation =[[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernamtion: %@ \nresponse: %@", operation, responseObject);
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            
            self.appDelegate.accessKey = responseObject[@"key"];
            self.appDelegate.userId = responseObject[@"data"][@"userId"];
            if ([responseObject[@"data"][@"userType"] isEqualToString:@"teacher"]) {
                self.appDelegate.userType = UserTypeTeacher;
                // for teacher
                [[UINavigationBar appearance]setBarTintColor:UIColorFromRGB(0x5cb0ee, 1)];
            }else{
                self.appDelegate.userType = UserTypeParent;
                // for parent
                [[UINavigationBar appearance]setBarTintColor:UIColorFromRGB(0xeba041, 1)];
            }
            

            //save username & password
            NSDictionary *data = @{KEY_USERNAME: account, KEY_PASSWORD: password};
            [Keychain save:KEY_USERNAME_PASSWORD data:data];
            
            
            
            //sign in im
            if (![[[EaseMob sharedInstance] chatManager] isAutoLoginEnabled]) {
                [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:self.appDelegate.userId password:[UtilHelper md5LowCase:password] completion:
                 ^(NSDictionary *loginInfo, EMError *error) {
                     if (loginInfo && !error) {
//                         [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:loginInfo];
                         [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                     }else{
                         NSLog(@"im login error %@", error);
                         switch (error.errorCode) {
                             case EMErrorServerNotReachable:
                                 [UIAlertView alertWithMessage: @"聊天组件连接服务器失败!"];
                                 break;
                             case EMErrorServerAuthenticationFailure:
                                 [UIAlertView alertWithMessage: @"聊天组件用户名或密码错误"];
                                 break;
                             case EMErrorServerTimeout:
                                 [UIAlertView alertWithMessage: @"聊天组件连接服务器超时!"];
                                 break;
                             default:
                                 NSLog(@"聊天组件登录错误");
                                 break;
                         }
                     }
                 } onQueue:nil];
            }
            if (self.userPhoto) {
                [self uploadTeacherPhoto];
            }else{
                [self loadUserData:self.appDelegate.accessKey userId:self.appDelegate.userId userType:self.appDelegate.userType];
            }
            
//            [self gotoMainView];
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
            [self enableAutoSignIn:NO];
        }
        
        self.view.userInteractionEnabled = YES;
//        [self.activityIndicator stopAnimating];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
        self.view.userInteractionEnabled = YES;
//        [self.activityIndicator stopAnimating];
        [self enableAutoSignIn:NO];
    }];
    self.view.userInteractionEnabled = NO;
    [self.activityIndicator setAnimatingWithStateOfOperation:opernation];
    
}

- (void)loadUserData:(NSString *)key userId:(NSString *) userId userType:(UserType)userType{
    
    NSString *uriString = nil;
    if (userType == UserTypeTeacher) {
        uriString = [NSString stringWithFormat:@"Teacher/%@.json", userId];
    }else {
        uriString = [NSString stringWithFormat:@"Parent/%@.json", userId];
    }
    NSDictionary *parameters = @{@"key": key};
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            self.appDelegate.user = responseObject[@"data"];
            
            NSArray *tags =@[self.appDelegate.userId, responseObject[@"data"][@"kClassId"]];
            [BPush setTags:tags];
//            [BPush setTag:@"1"];
            
            //load user photo
            operationQueue = [[NSOperationQueue alloc] init];
            NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadImage) object:nil];
            [operationQueue addOperation:op];
            
            [self enableAutoSignIn:YES];
            
            
            [self gotoMainView];
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
    }];
    
}

- (void)gotoMainView{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    UIViewController *centerController;
    switch (self.appDelegate.startUpPage) {
        case menuNotice:
            centerController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"NavNotice"];
            break;
        case menuRest:
                centerController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"NavRestList"];
            break;
        case menuCheckOn:
            centerController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"NavCheckOn"];
            break;
        case menuScore:
            centerController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"NavScoreParentView"];
            break;
        default:
            centerController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"NavMainView"];
            break;

    }
    
    
        MenuViewController *leftController = nil;
    
    /*
    if (appDelegate.userType == UserTypeTeacher) {
        leftController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"TeacherMenu"];
    }else {
        leftController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"ParentMenu"];
    }
     */
    leftController = (MenuViewController *)[storyboard instantiateViewControllerWithIdentifier:@"Menu"];
    
    MMDrawerController *drawerController = [[MMDrawerController alloc]initWithCenterViewController:centerController leftDrawerViewController:(UIViewController *)leftController];
    drawerController.restorationIdentifier = @"Drawer";
    [drawerController setMaximumLeftDrawerWidth:249.0];
    [drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    
    self.appDelegate.menuController = leftController;
    
    [self presentViewController:drawerController animated:YES completion:nil];
}

- (void)uploadTeacherPhoto{
    NSString *uriString = @"Account/0/changePhoto.json";
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey};
    
    [[NetworkAccessManager shareManager]POST:uriString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData *data = UIImageJPEGRepresentation(self.userPhoto, 1.0);
        [formData appendPartWithFileData:data name:@"photo" fileName:[NSString stringWithFormat:@"%@.jpg",[[NSProcessInfo processInfo] globallyUniqueString]] mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"upload photo result is %@, \n%@",operation, responseObject);
        [self loadUserData:self.appDelegate.accessKey userId:self.appDelegate.userId userType:self.appDelegate.userType];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"upload photo error is %@",error);
        [UIAlertView alertWithNetworkError];
    }];
}

- (IBAction)selectPhotoAction:(id)sender {
    NSLog(@"selectPhotoAction");
    UIActionSheet *actionSheet;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
        NSString *destructiveButtonTitle = NSLocalizedString(@"拍照", nil);
        NSString *otherButtonTitle = NSLocalizedString(@"从相册中选取", nil);
        actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:otherButtonTitle, nil];
    }else{
        NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
        NSString *destructiveButtonTitle = NSLocalizedString(@"从相册中选取", nil);
        actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:nil, nil];
    }
    [actionSheet showInView:self.view];
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"button index %zd", buttonIndex);
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        if (buttonIndex == 0) {
            // 拍照
            
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate =self;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
        }else if (buttonIndex == 1){
            // 从相册中选取
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate =self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }else{
        if (buttonIndex == 0) {
            // 从相册中选取
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate =self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }
    
}
#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSLog(@"pick a photo");
//    UIImage *image =  [info objectForKey:UIImagePickerControllerOriginalImage];
    NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];

    [picker dismissViewControllerAnimated:NO completion:^{
        NSLog(@"dismissViewControllerAnimated imagePicker");
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
            UIImage *preview = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
            
            SNSCropImageViewController *imageEditor = [[SNSCropImageViewController alloc] initWithNibName:@"SNSCropImage" bundle:nil cropRect:CGRectMake(0, 0, kCropPhotoSize, kCropPhotoSize)];
            
            imageEditor.noOptionButton = YES;
            imageEditor.sourceImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            imageEditor.previewImage = preview;
            
            imageEditor.doneCallback = ^(UIImage *editedImage, BOOL canceled){
                NSLog(@"imageEditor.doneCallback");
                if (!canceled) {
                    //                    self.userPhoto = editedImage;
                    UIGraphicsBeginImageContext(CGSizeMake(kCropPhotoSize, kCropPhotoSize));
                    [editedImage drawInRect:CGRectMake(0, 0, kCropPhotoSize, kCropPhotoSize)];
                    self.userPhoto = UIGraphicsGetImageFromCurrentImageContext();
                    self.userPhotoView.image = self.userPhoto;
                    UIGraphicsEndImageContext();
                }
                [self dismissViewControllerAnimated:NO completion:nil];
            };
            [self presentViewController:imageEditor animated:NO completion:nil];
        } failureBlock:^(NSError *error) {
            NSLog(@"error occour when read preview photo %@", error);
            
            SNSCropImageViewController *imageEditor = [[SNSCropImageViewController alloc] initWithNibName:@"SNSCropImage" bundle:nil cropRect:CGRectMake(0, 0, kCropPhotoSize, kCropPhotoSize)];

            
            imageEditor.sourceImage = [info objectForKey:UIImagePickerControllerOriginalImage];
//            imageEditor.previewImage = preview;
            
            imageEditor.doneCallback = ^(UIImage *editedImage, BOOL canceled){
                NSLog(@"imageEditor.doneCallback");
                if (!canceled) {
//                    self.userPhoto = editedImage;
                    UIGraphicsBeginImageContext(CGSizeMake(kCropPhotoSize, kCropPhotoSize));
                    [editedImage drawInRect:CGRectMake(0, 0, kCropPhotoSize, kCropPhotoSize)];
                    self.userPhoto = UIGraphicsGetImageFromCurrentImageContext();
                    self.userPhotoView.image = self.userPhoto;
                    UIGraphicsEndImageContext();
                }
                
                [self dismissViewControllerAnimated:NO completion:nil];
            };
            [self presentViewController:imageEditor animated:NO completion:nil];
        }];
        
        
    }];
    
}


-(BOOL)canAutoSignIn{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    return [defaults boolForKey:@"canAutoSignIn"];

}
-(void)enableAutoSignIn:(BOOL)enable{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    NSMutableDictionary *defaultcoordinate = [defaults objectForKey:@"default_coordinate"];
    
    [defaults setBool:enable forKey:@"canAutoSignIn"];
    [defaults synchronize];
}

-(void)loadImage{
    NSURL *photoUrl = [NSURL URLWithString:self.appDelegate.user[@"photo"]];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:photoUrl]];
    self.appDelegate.userPhoto = image;
//    [self.userPhoto setImage:image];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self signInAction:nil];
    return YES;
}

@end
